﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using WqLunTan.Filters;

namespace WqLunTan.Controllers
{
    /// <summary>
    /// 前台用户上传文件的控制器
    /// </summary>
    [Auth]
    public class UploadController : BaseController
    {
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <returns></returns>
        [HttpPost("upload/user_image")]
        public IActionResult UploadImage(IFormFile image)
        {
            if (image != null)
            {
                var env = HttpContext.RequestServices.GetService<IHostingEnvironment>();
                var root = env.WebRootPath;

                var day = DateTimeOffset.UtcNow.ToString("yyyy-MM-dd");

                var ext = image.FileName.Substring(image.FileName.LastIndexOf('.'));
                var name = $"{Guid.NewGuid().ToString("N")}{ext}";
                var filename = Path.Combine(root, "upload", "user_image", day, name);
                var fi = new FileInfo(filename);
                if (!Directory.Exists(fi.DirectoryName))
                {
                    Directory.CreateDirectory(fi.DirectoryName);
                }
                using (var fs = System.IO.File.Create(filename))
                {
                    image.CopyTo(fs);
                }
                var fileUrl = $"/upload/user_image/{day}/{name}";
                return Json(new { errno = 0, data = new List<string>() { fileUrl } });
            }
            return Json(new { errno = 1, data = new List<string>() { } });
        }
    }
}